import uuid
from django.core.cache import cache
from django.shortcuts import render
from rest_framework import viewsets,status
from rest_framework.response import Response
from rest_framework.exceptions import APIException,NotFound
from rest_framework.generics import ListAPIView,CreateAPIView,ListCreateAPIView
from .models import Book,Game,Movie,User
from App.serializers import BookSerializers,GameSerializers,MovieSerializers,UserSerializers
# Create your views here.
from .authentication import UserAuthentication
from .permissions import UserLoginPermission


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializers


# class GameCreatAPIView(ListAPIView): 只能get
#     queryset = Game.objects.all()
#     serializer_class = GameSerializers

# class GameCreatAPIView(CreateAPIView): 只能post
#     queryset = Game.objects.all()
#     serializer_class = GameSerializers

class GameCreatAPIView(ListCreateAPIView): #post 和get 都可以
    queryset = Game.objects.all()
    serializer_class = GameSerializers


class MovieViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializers
    authentication_classes = UserAuthentication, #验证登录 用户名或者密码是否正确
    permission_classes = UserLoginPermission,
    #验证你是否登录了

class UserCreateApiView(CreateAPIView):
    serializer_class = UserSerializers
    def post(self, request, *args, **kwargs):
        action = request.query_params.get('action')
        print(action)
        if action == "register":
            return self.create(request,*args,**kwargs)
        elif action == "login":
            return self.do_login(request, *args, **kwargs)
        else:
            raise APIException(detail="要么你就登录要么你就注册")

    def do_login(self, request, *args, **kwargs):
        u_name = request.data.get("u_name")
        u_password = request.data.get("u_password")
        try:
            user = User.objects.get(u_name=u_name)
            print(user.id)
        except User.DoesNotExist as e:
            raise NotFound(detail="用户名不存在")
            #抛出错误信息在 rest_framework 下面的exceptions.py下面查看
        if user.u_password != u_password:
            raise APIException(detail="用户密码错误")

        token = uuid.uuid4().hex
        print(token)

        cache.set(token,user.id,timeout=60*60*24*7)

        data = {
            "status":status.HTTP_200_OK,
            "msg":"登录成功注意查看你的token",
            "token":token
        }
        return Response(data)





